<template>
  <div class="single-ingot-detail">
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeTable ref="gridRef" v-bind="gridOption">
        <template #singleIngotSlot="{ row }">
          <div class="flex-wrap">
            <div v-for="(item, index2) in row.itemArr" :key="index2" class="flex-item">
              <div class="serial-number" :style="{ background: item.bjColor }">
                {{ item.name }}
              </div>
              <div class="switch-box">
                <el-switch
                  v-model="item.zhuangTai"
                  inline-prompt
                  active-text="开"
                  inactive-text="关"
                  active-color="#49BEFF"
                  inactive-color="#C7C9C6"
                  :disabled="true"
                />
              </div>
            </div>
          </div>
        </template>
      </BasicVxeTable>
    </BasicCard>
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeTable ref="gridRefBroken" v-bind="gridOptionBroken"> </BasicVxeTable>
    </BasicCard>
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeTable ref="gridRefRecord" v-bind="gridOptionRecord"> </BasicVxeTable>
    </BasicCard>
  </div>
</template>
<script setup lang="ts">
  import dayjs from 'dayjs'
  import { formatDuration } from '@/utils/common/date'
  import { MachineListRowVO, BrokenListRowVO, RecordListRowVO } from '../../types'
  import { MachineListTableColumns, BrokenTableColumns, RecordTableColumns } from '../../data'
  import { useUserStore } from '@/store/modules/user'

  import {
    getCuShaDanDingShiShiXinXi,
    postDanDingDuanTouTongJi,
    postGuanBiJianChaJiLu_CS
  } from '@/api/shengChanJianShi'
  import { getJiTaiTheGongYi } from '@/api/gongGongChaXun'

  const { t } = useI18n()
  const gridOption = reactive<BasicGridProps>({
    maxHeight: 500,
    extraConfig: {
      title: t('custom.单锭详情'),
      isCustom: false,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `single-ingot`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    showOverflow: true,
    proxyConfig: {
      autoLoad: false,
      // showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getList()
        }
      }
    },
    columns: MachineListTableColumns
  })

  const userStore = useUserStore()
  const csId = userStore.getSycConstant('cuShaID')

  const seleJiTaiIDs2 = ref<any[]>([])
  const seleJiTaiIDs = ref<any[]>([])
  const allJiTaiIDs = ref<any[]>([])
  const jitaiText = ref()
  const jitaiList = ref<MachineListRowVO[]>([])
  const getProcessInfo = () => {
    getJiTaiTheGongYi(csId).then((res: any) => {
      jitaiList.value = res
      let arr = jitaiList.value
        .map((value) => {
          return value.machineName
        })
        .sort((a: any, b: any) => {
          return a - b
        })
      seleJiTaiIDs2.value = jitaiList.value.map((value) => {
        return value.id
      })
      allJiTaiIDs.value = JSON.parse(JSON.stringify(seleJiTaiIDs2.value))
      seleJiTaiIDs.value = JSON.parse(JSON.stringify(seleJiTaiIDs2.value))
      jitaiText.value = arr.join(',')
      //   this.$refs.timeSelect2.init(this.$cookies.get('cuShaID'))
      //   this.$refs.timeSelect.init(this.$cookies.get('cuShaID'))
      gridRef.value?.$grid?.commitProxy('query')
      gridRefBroken.value?.$grid?.commitProxy('query')
      gridRefRecord.value?.$grid?.commitProxy('query')
    })
  }

  const clearTimeSet = ref()
  const gridRef = ref<BasicGridInstance>()
  const getList = () => {
    return new Promise<any[]>((resolve) => {
      getCuShaDanDingShiShiXinXi(seleJiTaiIDs.value).then((res: any) => {
        let jitaiArr = res.map((value) => {
          let itemArr: any = []
          // 差集
          let arr1 = value.rightBreaks.filter((item) => !value.leftBreaks.includes(item))
          // 交集
          let arr2 = value.rightBreaks.filter((item) => value.leftBreaks.includes(item))
          value.leftBreaks.forEach((value2) => {
            let bool = arr2.every((value3) => {
              return value3 !== value2
            })
            if (bool == true) {
              itemArr.push({
                name: value2,
                zhuangTai: true,
                bjColor: '#ff4545'
              })
            } else {
              itemArr.push({
                name: value2,
                zhuangTai: false,
                bjColor: '#ff4545'
              })
            }
          })
          if (arr1.length !== 0) {
            arr1.forEach((value) => {
              itemArr.push({
                name: value,
                zhuangTai: false,
                bjColor: '#0BC15E'
              })
            })
          }
          itemArr.sort((a, b) => {
            return a.name - b.name
          })
          return {
            machineDocumentId: value.machineDocumentId,
            machineName: value.machineName,
            machineNo: value.machineNo,
            breakCount: value.breakCount,
            leftBreaks: value.leftBreaks,
            rightBreaks: value.rightBreaks,
            itemArr: itemArr
          }
        })

        resolve(
          jitaiArr
            .filter((value) => {
              return value.itemArr.length != 0
            })
            .sort((a, b) => {
              return b.breakCount - a.breakCount
            })
        )
      })
    })
  }

  // 粗纱重复断头
  const gridRefBroken = ref<BasicGridInstance>()
  const gridOptionBroken = reactive<BasicGridProps>({
    maxHeight: 500,
    extraConfig: {
      title: t('custom.粗纱重复断头'),
      isCustom: false,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `single-ingot-broken`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    showOverflow: true,
    proxyConfig: {
      autoLoad: false,
      // showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getBrokenList()
        }
      }
    },
    columns: BrokenTableColumns
  })
  const getBrokenList = () => {
    return new Promise<BrokenListRowVO[]>((resolve) => {
      postDanDingDuanTouTongJi({
        tsIdStart: '25070901',
        tsIdEnd: '25070901',
        machineDocumentIds: seleJiTaiIDs2.value
      }).then((res: any) => {
        resolve(
          res.map((value) => {
            return {
              machineDocumentId: value.machineDocumentId,
              machineName: value.machineName,
              machineNo: value.machineNo,
              personName: value.personName,
              positionId: value.positionId,
              breakCount: value.breakCount,
              duration: value.duration === null ? value.duration : formatDuration(value.duration)
            }
          })
        )
      })
    })
  }

  // 关闭检测记录
  const gridRefRecord = ref<BasicGridInstance>()
  const gridOptionRecord = reactive<BasicGridProps>({
    maxHeight: 500,
    extraConfig: {
      title: t('custom.关闭检测记录'),
      isCustom: false,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `single-ingot-record`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    showOverflow: true,
    proxyConfig: {
      autoLoad: false,
      // showLoading: false, // 关闭加载中
      ajax: {
        query: () => {
          // 默认接收 Promise<any[]>
          return getRecordList()
        }
      }
    },
    columns: RecordTableColumns
  })

  const getRecordList = () => {
    return new Promise<RecordListRowVO[]>((resolve) => {
      postGuanBiJianChaJiLu_CS({
        tsIdStart: '25070901',
        tsIdEnd: '25070901',
        machineDocumentIds: allJiTaiIDs.value
      }).then((res: any) => {
        resolve(
          res.map((value) => {
            return {
              machineDocumentId: value.machineDocumentId,
              machineName: value.machineName,
              machineNo: value.machineNo,
              personName: value.personName,
              positionId: value.positionId,
              startTime:
                value.startTime === null
                  ? value.startTime
                  : dayjs(value.startTime).format('YYYY-MM-DD HH:mm:ss'),
              duration: value.duration === null ? value.duration : formatDuration(value.duration)
            }
          })
        )
      })
    })
  }

  onUnmounted(() => {
    clearInterval(clearTimeSet.value)
  })

  onMounted(() => {
    getProcessInfo()
    clearTimeSet.value = setInterval(() => {
      gridRef.value?.$grid?.commitProxy('query')
    }, 10000)
  })
</script>
<style scoped lang="scss">
  .detail-table {
    padding: 20px;
    margin-bottom: 20px;
    background-color: #fff;

    .vxe-grid {
      margin-top: 25px;
    }
  }

  :deep(.vxe-cell) {
    height: auto !important;
  }

  .flex-wrap {
    display: flex;
    flex-wrap: wrap;

    .flex-item {
      width: 74px;
      text-align: center;

      .serial-number {
        width: 74px;
        height: 32px;
        line-height: 32px;
        color: #fff;
        box-shadow: inset -1px 0 0 0 #fff;
      }
    }
  }
</style>
